package com.bawei.common.mvi

import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.launch

/**
 * @author ZhangRuiPeng
 * @description:
 */
abstract class BaseActivity<V : ViewBinding, VM : BaseViewModel<*,*>> : AppCompatActivity(){
    protected val v : V by lazy { createViewBinding() }
    protected val vm : VM by lazy { createViewModel() }
    protected val inflater : LayoutInflater by lazy { LayoutInflater.from(this) }

    abstract fun createViewBinding() : V
    abstract fun createViewModel() : VM

     override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(v.root)
        bindRequestState()
        bindUiState()
    }

    //绑定requsetstate状态方法
    fun bindRequestState(){
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                vm.realContainer.requestState
                    .collect{
                        if (it.requestState){
                            requsetStateShow()
                        }else if (it.successState){
                            successStateShow()
                        }else if (it.error){
                            errorStateShow()
                        }
                    }
            }


        }

    }


    //UI 数据状态处理方法
    abstract fun bindUiState()

    //request状态处理
    fun requsetStateShow(){
        ToastUtils.showShort("请求开始")
    }
    //success状态处理
    fun successStateShow(){
        ToastUtils.showShort("请求成功")
    }
    //error状态处理
    fun errorStateShow(){
        ToastUtils.showShort("请求失败")
    }




}